/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate.dao;

import hibernate.entity.Accounts;
import hibernate.entity.Functions;
import hibernate.entity.Roles;
import java.util.HashMap;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author NDH1
 */
public class RoleDAO extends AbstractDAO {

    void create(Roles r) {
        Session session;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            Transaction t = session.beginTransaction();

            session.save(r);
            t.commit();
        } catch (Exception e) {
            System.out.println("");
        }
    }

    public List<Roles> readAll() {
        session = HibernateUtil.getSessionFactory().openSession();
        query = session.createQuery("from Roles");
        return query.list();
    }

    public Roles getRoleByName(String name) {
        for (Roles r : readAll()) {
            if (r.getRoleName().equalsIgnoreCase(name)) {
                return r;
            }
        }
        return null;
    }

    public List<Functions> functionInRole(Roles role) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            query = session.createQuery("from Functions as f inner join f.functionRoleses as fr "
                    + "with fr.roles = :role");
            query.setParameter("role", role);
            return query.list();
        } catch (Exception e) {
            return null;
        }
    }

    public List<Functions> functionInRole(int roleID) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            query = session.createQuery("from Functions as f inner join f.functionRoleses as fr "
                    + "with fr.roles.roleID = :role");
            query.setParameter("role", roleID);
            return query.list();
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {

        try {
            RoleDAO dao = new RoleDAO();
            Accounts a;
        } catch (Exception ex) {
            System.out.println("");
        }
    }

    public boolean isLoginHaveRole(Accounts lgn, Roles role) {
       return (lgn.getRoleses().contains(role));
    }
}
